package com.jeesite.modules.sys.web;

import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.modules.sys.utils.UserUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.service.OfficeService;

/**
 * 组织机构表Controller
 * @author ccz
 * @version 2025-03-19
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/office")
public class OfficeController extends BaseController {

	@Autowired
	private OfficeService officeService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public Office get(String officeCode, boolean isNewRecord) {
		return officeService.get(officeCode, isNewRecord);
	}

	/**
	 * 管理主页
	 */
	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = "index")
	public String index(Office office, Model model) {
		model.addAttribute("office", office);
		return "modules/sys/officeIndex";
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = {"list", ""})
	public String list(Office office, Model model) {
		model.addAttribute("office", office);
		return "modules/sys/officeList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public List<Office> listData(Office office) {
		if (StringUtils.isBlank(office.getParentCode())) {
			office.setParentCode(Office.ROOT_CODE);
		}
		if (StringUtils.isNotBlank(office.getViewCode())){
			office.setParentCode(null);
		}
		if (StringUtils.isNotBlank(office.getOfficeName())){
			office.setParentCode(null);
		}
		if (StringUtils.isNotBlank(office.getFullName())){
			office.setParentCode(null);
		}
		if (StringUtils.isNotBlank(office.getOfficeType())){
			office.setParentCode(null);
		}
		if (StringUtils.isNotBlank(office.getLeader())){
			office.setParentCode(null);
		}
		if (StringUtils.isNotBlank(office.getPhone())){
			office.setParentCode(null);
		}
		if (StringUtils.isNotBlank(office.getAddress())){
			office.setParentCode(null);
		}
		if (StringUtils.isNotBlank(office.getZipCode())){
			office.setParentCode(null);
		}
		if (StringUtils.isNotBlank(office.getEmail())){
			office.setParentCode(null);
		}
		if (StringUtils.isNotBlank(office.getRemarks())){
			office.setParentCode(null);
		}
		List<Office> list = officeService.findList(office);
		return list;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = "form")
	public String form(Office office, Model model) {
		// 创建并初始化下一个节点信息
		office = createNextNode(office);
		model.addAttribute("office", office);
		return "modules/sys/officeForm";
	}
	
	/**
	 * 创建并初始化下一个节点信息，如：排序号、默认值
	 */
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "createNextNode")
	@ResponseBody
	public Office createNextNode(Office office) {
		if (StringUtils.isNotBlank(office.getParentCode())){
			office.setParent(officeService.get(office.getParentCode()));
		}
		if (office.getIsNewRecord()) {
			Office where = new Office();
			where.setParentCode(office.getParentCode());
			Office last = officeService.getLastByParentCode(where);
			// 获取到下级最后一个节点
			if (last != null){
				office.setTreeSort(last.getTreeSort() + 30);
				office.setOfficeCode(IdGen.nextCode(last.getOfficeCode()));
			}else if (office.getParent() != null){
				office.setOfficeCode(office.getParent().getOfficeCode() + "001");
			}
		}
		// 以下设置表单默认数据
		if (office.getTreeSort() == null){
			office.setTreeSort(Office.DEFAULT_TREE_SORT);
		}
		return office;
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("sys:office:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated Office office) {
		officeService.save(office);
		return renderResult(Global.TRUE, text("保存组织机构表成功！"));
	}
	
	/**
	 * 删除数据
	 */
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(Office office) {
		officeService.delete(office);
		return renderResult(Global.TRUE, text("删除组织机构表成功！"));
	}
	
	/**
	 * 获取树结构数据
	 * @param excludeCode 排除的Code
	 * @param parentCode 设置父级编码返回一级
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @return
	 */
	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = "treeData")
	@ResponseBody
	public List<Map<String, Object>> treeData(String excludeCode, String parentCode, String isShowCode) {
		List<Map<String, Object>> mapList = ListUtils.newArrayList();
		Office where = new Office();
		where.setStatus(Office.STATUS_NORMAL);
		if (StringUtils.isNotBlank(parentCode)){
			where.setParentCode(parentCode);
		}
		List<Office> list = officeService.findList(where);
		for (int i=0; i<list.size(); i++){
			Office e = list.get(i);
			// 过滤非正常的数据
			if (!Office.STATUS_NORMAL.equals(e.getStatus())){
				continue;
			}
			// 过滤被排除的编码（包括所有子级）
			if (StringUtils.isNotBlank(excludeCode)){
				if (e.getId().equals(excludeCode)){
					continue;
				}
				if (e.getParentCodes().contains("," + excludeCode + ",")){
					continue;
				}
			}
			Map<String, Object> map = MapUtils.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentCode());
			map.put("name", StringUtils.getTreeNodeName(isShowCode, e.getOfficeCode(), e.getOfficeName()));
			map.put("isParent", !e.getIsTreeLeaf());
			mapList.add(map);
		}
		return mapList;
	}

	/**
	 * 修复表结构相关数据
	 */
	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "fixTreeData")
	@ResponseBody
	public String fixTreeData(Office office){
		if (!UserUtils.getUser().isAdmin()){
			return renderResult(Global.FALSE, "操作失败，只有管理员才能进行修复！");
		}
		officeService.fixTreeData();
		return renderResult(Global.TRUE, "数据修复成功");
	}






}